import os
from flask import Flask, render_template, request, redirect, url_for, session, flash, send_from_directory
import config



app = Flask(__name__)
app.config['SECRET_KEY'] = "111111"
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:20170793@localhost:3306/cwriter'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config.from_object(config)



@app.route('/')
def index():
    return render_template('index.html')


@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('log.html')
    else:
        username = request.form.get('username')
        password = request.form.get('password')

        user = User.query.filter(and_(User.username == username, User.password == password)).first()
        if user:
            session['user_id'] = user.id
            # session.permanent = True
            return redirect(url_for('index', user=user))
        else:
            flash("哎呀，用户名或者密码错误……")
            return redirect(url_for('login'))



@app.route('/admin')
def admin():
    boards = Board.query.all()
    return render_template('admin.html', boards=boards)


@app.route('/admin_login/', methods=['GET', 'POST'])
def admin_login():
    if request.method == 'GET':
        return render_template('admin_log.html')
    else:
        username = request.form.get('username')
        password = request.form.get('password')

        user = User.query.filter(and_(User.username == username, User.password == password)).first()
        if user:
            session['user_id'] = user.id
            # session.permanent = True
            return redirect(url_for('admin', user=user))
        else:
            flash("哎呀，用户名或者密码错误……")
            return redirect(url_for('admin_login'))


@app.route('/logout')
def logout():
    del session['user_id']
    return redirect(url_for('login'))